import { Card, Divider, Button, Form, Input, message } from 'antd'
import styles from './index.module.scss'
import { login } from '@/api/login'

import { useDispatch } from 'react-redux'
import { setInfo } from '@/store/modules/user'
import { useNavigate, useLocation } from 'react-router-dom'
import { getUserInfo } from '@/api/user'

export default function Login () {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const location = useLocation()

  const onFinish = async (values: any) => {
    const res1 = await login(values)
    if (res1.code === 200) {
      //存储token到仓库中
      dispatch(setInfo(res1.data))

      // 获取用户信息
      const res2 = await getUserInfo()
      console.log(res2.data)

      dispatch(setInfo({ ...res1.data, ...res2.data }))

      // 提示信息
      message.success(res1.message, 1, () => {
        // navigate('/')
        if (location.search) {
          const searchParams = new URLSearchParams(location.search)
          navigate(searchParams.get('redirect') ?? '/')
        } else {
          navigate('/')
        }
      })
    } else {
      message.error(res1.message, 1)
    }
  }

  type FieldType = {
    adminname?: string
    password?: string
  }

  return (
    <div className={styles.root}>
      <Card className='box-card'>
        <h2 style={{ textAlign: 'center' }}>嗨购商城后台管理系统</h2>
        <Divider />
        <Form
          name='basic'
          style={{ maxWidth: 600 }}
          initialValues={{ adminname: 'admin', password: '123456' }}
          onFinish={onFinish}
          autoComplete='off'
          labelAlign='left'
          size='large'
        >
          <Form.Item<FieldType>
            label='用户名'
            name='adminname'
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            rules={[{ required: true, message: '用户名不能为空' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item<FieldType>
            label='密码'
            name='password'
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            rules={[{ required: true, message: '密码不能为空' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item>
            <Button
              style={{ width: 300, margin: '10px 70px', textAlign: 'center' }}
              type='primary'
              htmlType='submit'
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
